import './index.css'
import * as THREE from 'three'
import {
    OrbitControls
} from 'three/examples/jsm/controls/OrbitControls'
import CANNON from 'cannon'


/**
 * Size
 */
const Size = {
    width: window.innerWidth,
    height: window.innerHeight
}


/**
 * Camera
 */
const camera = new THREE.PerspectiveCamera(75, Size.width / Size.height, 0.1, 100)
camera.position.set(0, 4, 15)

/**
 * Scene
 */
const scene = new THREE.Scene()


/**
 * Material
 */
const material = new THREE.MeshStandardMaterial({
    color: 0xffffff
})


/**
 * Objects
 */
const planeGoemetry = new THREE.PlaneGeometry(20, 20)
const plane = new THREE.Mesh(planeGoemetry, material)
plane.rotation.set(-Math.PI / 2, 0, 0)
plane.receiveShadow = true

const sphere = new THREE.Mesh(new THREE.SphereGeometry(1, 16, 16), material)
sphere.position.setY(1)
sphere.castShadow = true

scene.add(plane, sphere)


/**
 * Lights
 */
const ambientLight = new THREE.AmbientLight('#ffffff', 0.5)
const directionalLight = new THREE.DirectionalLight('#ffffff', 3)
directionalLight.position.set(-5, 6, 0)
directionalLight.castShadow = true
const directionalLightHelper = new THREE.DirectionalLightHelper(directionalLight)
scene.add(ambientLight, directionalLight, directionalLightHelper)


/**
 * Physics
 */
const world = new CANNON.World()
world.gravity.set(0, -9.82, 0)

/**
 * 摩擦力及弹性
 */
const defaultMaterial = new CANNON.Material("default")
const defaultContactMaterial = new CANNON.ContactMaterial(defaultMaterial,defaultMaterial,{
    friction:0.1,
    restitution:0.6
})
world.addContactMaterial(defaultContactMaterial)



const sphereShape = new CANNON.Sphere(1)
const sphereBody = new CANNON.Body({
    mass: 1,
    position: new CANNON.Vec3(0, 3, 0),
    shape: sphereShape,
    material:defaultMaterial
})
world.addBody(sphereBody)

const floorShape = new CANNON.Plane()
const floorBody = new CANNON.Body({
    mass: 0, //固定
    shape: floorShape,
    material:defaultMaterial
})
// 跟平面一样 旋转
//new CANNON.Vec3(1, 0, 0)旋转向量     -Math.PI / 2 角度
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
world.addBody(floorBody)



/**
 * Renderer
 */
const canvas = document.querySelector('canvas.webgl')
const renderer = new THREE.WebGLRenderer({
    canvas
})
renderer.setSize(Size.width, Size.height)
renderer.shadowMap.enabled = true


/**
 * OrbitControls
 */
const controls = new OrbitControls(camera, canvas)
controls.enableDamping = true


/**
 * Update
 */
const clock = new THREE.Clock()
let currentElpasedTime = 0
const tick = () => {
    controls.update();
    const elpasedTime = clock.getElapsedTime()
    const deltaTime = elpasedTime - currentElpasedTime
    currentElpasedTime = elpasedTime

    /**
     * Physics
     */
    world.step(1 / 60, deltaTime, 3)
    sphere.position.copy(sphereBody.position)

    renderer.render(scene, camera)
    requestAnimationFrame(tick)
}
tick()